package com.zjeav.lingjiao.base.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.widget.Toast;

import com.dalimao.corelibrary.utils.NetWorkUtils;
import com.dalimao.corelibrary.view.SelfDialog;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.utils.CommonProgressDialog;
import com.zjeav.lingjiao.base.utils.UIUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载apk
 */
public class DownloadApk extends Activity {

    private CommonProgressDialog pBar; //app更新
    private Context context;
    private Activity activity;
    private String downloadName;//文件名

    public DownloadApk(Context context, String downloadName, Activity activity) {
        this.context = context;
        this.downloadName = downloadName;
        this.activity = activity;
    }

    /**
     * 升级系统
     *
     * @param content 更新说明
     * @param url
     */
    public void ShowDialog(String content, final String url,String appVersionName) {

        final UpdateAppDialog updateAppDialog = new UpdateAppDialog(context);
        updateAppDialog.setMessage(content);
        updateAppDialog.setVersioncodename(appVersionName);
        updateAppDialog.setYesOnclickListener("立即安装", new UpdateAppDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                updateAppDialog.dismiss();
                if (NetWorkUtils.isNetworkConnected(context)){
                    if(NetWorkUtils.isWifiConnected(context)){
                        download(url);
                    }else {
                        final SelfDialog selfDialog = new SelfDialog(context);
                        selfDialog.setTitle("提示");
                        selfDialog.setMessage("检测到您当前网络非wifi?，继续下载可能会使用数据流量。");
                        selfDialog.setYesOnclickListener("继续下载", new SelfDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                selfDialog.dismiss();
                                download(url);

                            }
                        });
                        selfDialog.setNoOnclickListener("稍后下载", new SelfDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.show();
                    }
                }else {
                    UIUtils.showToast("当前无网络连接");
                }


            }
        });
        updateAppDialog.setNoOnclickListener("", new UpdateAppDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                updateAppDialog.dismiss();
            }
        });
        updateAppDialog.show();
    }

    private void download(String url){

        pBar = new CommonProgressDialog(context);
        pBar.setCanceledOnTouchOutside(false);
        pBar.setTitle("正在下载");
        pBar.setCustomTitle(LayoutInflater.from(
                context).inflate(
                R.layout.title_dialog, null));
        pBar.setMessage("正在下载");
        pBar.setIndeterminate(true);
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pBar.setCancelable(true);
        final DownloadTask downloadTask = new DownloadTask(
                context);
        downloadTask.execute(url);
        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                downloadTask.cancel(true);
            }
        });
    }

    /**
     * 下载应用
     *
     * @author Administrator
     */
    class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    String path = Environment.getExternalStorageDirectory()+File.separator+downloadName;
                    file = new File(path);

                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(context, "sd卡未挂载",
                            Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                    ignored.printStackTrace();
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();

            new Handler().postDelayed(new Runnable() {
                public void run() {
                    pBar.dismiss();
                    update();
                }
            }, 2000);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                //有注册权限且用户允许安装
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    update();
                } else {
                    //将用户引导至安装未知应用界面。
                    Uri packageURI = Uri.parse("package:"+getPackageName());//设置包名，可直接跳转当前软件的设置页面
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
                    startActivityForResult(intent, 10012);
                }
                break;
        }
    }

    public void update() {

        String strfileprovider = "com.zjeav.lingjiao.fileprovider";
        String strappName = "lingo.apk";

        try {
            String path = Environment.getExternalStorageDirectory()+File.separator+downloadName;
            File apkFile = new File(path);
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上

                // strfileprovider 在AndroidManifest中的android:authorities值

                Uri apkUri = FileProvider.getUriForFile(context, strfileprovider, apkFile);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
